<template>
  <div class="xml-to-mermaid-container">
    <div class="main-content">
      <!-- 左侧输入区 -->
      <div class="left-panel">
        <n-card title="XML流程图生成工具" class="input-card">
          <n-space vertical size="large">
            <!-- XML获取方式选择 -->
            <div class="section">
              <n-text class="section-title">XML获取方式</n-text>
              <n-radio-group v-model:value="inputMethod" size="large">
                <n-space vertical>
                  <n-radio value="database" label="从Oracle数据库获取" />
                  <n-radio value="upload" label="上传XML文件" />
                  <n-radio value="text" label="直接输入XML" />
                </n-space>
              </n-radio-group>
            </div>

            <!-- 数据库方式 -->
            <div class="section" v-if="inputMethod === 'database'">
              <n-text class="section-title">数据库连接</n-text>
              <n-space vertical>
                <n-space>
                  <n-button
                    size="small"
                    :type="dbStatus === 'connected' ? 'success' : 'error'"
                    :loading="isTestingConnection"
                    @click="testConnection"
                  >
                    <template #icon>
                      <n-icon>
                        <DatabaseIcon />
                      </n-icon>
                    </template>
                    {{ dbStatusText }}
                  </n-button>

                  <n-button
                    size="small"
                    :disabled="dbStatus !== 'connected'"
                    :loading="isLoadingWorkflows"
                    @click="loadWorkflowList"
                  >
                    <template #icon>
                      <n-icon>
                        <RefreshIcon />
                      </n-icon>
                    </template>
                    刷新流程列表
                  </n-button>
                </n-space>

                <div v-if="workflowList.length > 0">
                  <n-text class="section-title">选择工作流程</n-text>
                  <n-select
                    v-model:value="selectedWorkflow"
                    placeholder="请选择要生成流程图的工作流"
                    :options="workflowOptions"
                    clearable
                    filterable
                    :filter="
                      (pattern, option) => {
                        const searchText = option.searchText || option.label;
                        return searchText.toLowerCase().includes(pattern.toLowerCase());
                      }
                    "
                  />
                </div>
              </n-space>
            </div>

            <!-- 文件上传方式 -->
            <div class="section" v-if="inputMethod === 'upload'">
              <n-text class="section-title">上传XML文件</n-text>
              <n-upload
                :file-list="fileList"
                :max="1"
                accept=".xml,.txt"
                @change="handleFileChange"
                @remove="handleFileRemove"
              >
                <n-upload-dragger>
                  <div style="margin-bottom: 12px">
                    <n-icon size="48" :depth="3">
                      <UploadIcon />
                    </n-icon>
                  </div>
                  <n-text style="font-size: 16px"> 点击或者拖动文件到该区域来上传</n-text>
                  <n-p depth="3" style="margin: 8px 0 0 0"> 支持 .xml 和 .txt 格式的文件</n-p>
                </n-upload-dragger>
              </n-upload>
            </div>

            <!-- 文本输入方式 -->
            <div class="section" v-if="inputMethod === 'text'">
              <n-text class="section-title">XML内容</n-text>
              <n-input
                v-model:value="xmlContent"
                type="textarea"
                placeholder="请粘贴XML内容..."
                :rows="12"
                clearable
                show-count
              />
            </div>

            <!-- 生成按钮 -->
            <div class="section">
              <n-space>
                <n-button
                  type="primary"
                  size="large"
                  :disabled="!canGenerate"
                  :loading="isGenerating"
                  @click="generateMermaid"
                >
                  <template #icon>
                    <n-icon>
                      <DiagramIcon />
                    </n-icon>
                  </template>
                  生成流程图
                </n-button>

                <n-button size="large" @click="clearAll">
                  <template #icon>
                    <n-icon>
                      <ClearIcon />
                    </n-icon>
                  </template>
                  清空
                </n-button>
              </n-space>
            </div>
          </n-space>
        </n-card>
      </div>

      <!-- 右侧结果区 -->
      <div class="right-panel">
        <n-card title="生成结果" class="result-card">
          <template #header-extra>
            <n-space>
              <n-button size="small" @click="copyMermaidCode" :disabled="!mermaidCode">
                <template #icon>
                  <n-icon>
                    <CopyIcon />
                  </n-icon>
                </template>
                复制代码
              </n-button>
              <n-button size="small" @click="downloadMermaidCode" :disabled="!mermaidCode">
                <template #icon>
                  <n-icon>
                    <DownloadIcon />
                  </n-icon>
                </template>
                下载
              </n-button>
            </n-space>
          </template>

          <n-tabs type="line" animated v-model:value="activeTab">
            <n-tab-pane name="preview" tab="流程图预览">
              <div class="mermaid-preview" v-if="mermaidCode">
                <div class="preview-header">
                  <n-space>
                    <n-button size="small" @click="openFullscreen" :disabled="!mermaidCode">
                      <template #icon>
                        <n-icon>
                          <ExpandIcon />
                        </n-icon>
                      </template>
                      全屏查看
                    </n-button>
                    <n-button size="small" @click="downloadImage" :disabled="!mermaidCode">
                      <template #icon>
                        <n-icon>
                          <ImageIcon />
                        </n-icon>
                      </template>
                      下载SVG
                    </n-button>
                  </n-space>
                </div>

                <div class="section">
                  <n-space style="margin-left: 5px;">
                    <n-checkbox v-model:checked="showProcessName">
                      显示流程名
                    </n-checkbox>
                    <n-checkbox v-model:checked="showCancelledSteps">
                      显示已取消环节
                    </n-checkbox>
                    <n-checkbox v-model:checked="showRejectedSteps">
                      显示已退回环节
                    </n-checkbox>
                  </n-space>
                </div>

                <div
                  ref="mermaidContainer"
                  class="mermaid-container"
                  role="img"
                  aria-label="工作流程图"
                  aria-describedby="mermaid-description"
                ></div>
                <div id="mermaid-description" class="sr-only">
                  这是一个基于XML数据生成的工作流程图，显示了各个状态之间的转换关系。
                </div>
              </div>
              <n-empty v-else description="暂无流程图" />
            </n-tab-pane>

            <n-tab-pane name="code" tab="Mermaid代码">
              <n-input
                v-model:value="mermaidCode"
                type="textarea"
                :rows="20"
                readonly
                placeholder="生成的Mermaid代码将显示在这里..."
              />
            </n-tab-pane>

            <n-tab-pane name="transitions" tab="解析结果">
              <n-data-table
                :columns="transitionColumns"
                :data="transitions"
                :pagination="false"
                size="small"
                :max-height="400"
                v-if="transitions.length > 0"
              />
              <n-empty v-else description="暂无解析结果" />
            </n-tab-pane>
          </n-tabs>
        </n-card>
      </div>
    </div>

    <!-- 全屏模态框 -->
    <n-modal
      v-model:show="showFullscreen"
      preset="card"
      title="流程图全屏预览"
      class="fullscreen-modal"
      :style="{ width: '95vw', height: '90vh' }"
      :closable="true"
      :mask-closable="true"
    >
      <template #header-extra>
        <n-space>
          <n-button size="small" @click="downloadImage">
            <template #icon>
              <n-icon>
                <ImageIcon />
              </n-icon>
            </template>
            下载SVG
          </n-button>
          <n-button size="small" @click="showFullscreen = false">
            <template #icon>
              <n-icon>
                <CloseIcon />
              </n-icon>
            </template>
            关闭
          </n-button>
        </n-space>
      </template>

      <div class="fullscreen-content">
        <div
          ref="fullscreenMermaidContainer"
          class="fullscreen-mermaid-container"
          role="img"
          aria-label="工作流程图全屏视图"
        ></div>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, nextTick, watch } from 'vue';
  import { useMessage } from 'naive-ui';
  import {
    CloudUpload as UploadIcon,
    Analytics as DiagramIcon,
    Copy as CopyIcon,
    Download as DownloadIcon,
    Trash as ClearIcon,
    Server as DatabaseIcon,
    Refresh as RefreshIcon,
    Expand as ExpandIcon,
    Image as ImageIcon,
    Close as CloseIcon,
  } from '@vicons/ionicons5';
  import { invoke } from '@tauri-apps/api/core';
  import type { DataTableColumns, UploadFileInfo } from 'naive-ui';
  import mermaid from 'mermaid';
  import { debounce } from 'lodash-es';

  // 类型定义
  interface Transition {
    name: string;
    alias: string;
    fromState: string;
    toState: string;
    description?: string;
  }

  interface WorkflowModel {
    wfid?: string;
    wfname?: string;
    WFID?: string;
    WFNAME?: string;

    [key: string]: any;
  }

  interface DatabaseSettings {
    host: string;
    port: number;
    database: string;
    username: string;
    password: string;
  }

  interface UserSettings {
    database: DatabaseSettings;
  }

  interface WorkflowXmlResult {
    wfcontent?: string;
    WFCONTENT?: string;
    WfContent?: string;
  }

  // 响应式数据
  const message = useMessage();
  const inputMethod = ref<'database' | 'upload' | 'text'>('text');
  const xmlContent = ref('');
  const fileList = ref<UploadFileInfo[]>([]);
  const mermaidCode = ref('');
  const transitions = ref<Transition[]>([]);
  const isGenerating = ref(false);
  const isLoadingWorkflows = ref(false);
  const isTestingConnection = ref(false);
  const dbStatus = ref<'connected' | 'disconnected' | 'unknown'>('unknown');
  const mermaidContainer = ref<HTMLDivElement | null>(null);
  const fullscreenMermaidContainer = ref<HTMLDivElement | null>(null);
  const activeTab = ref('preview');
  const showFullscreen = ref(false);
  const workflowList = ref<WorkflowModel[]>([]);
  const selectedWorkflow = ref<string>('');
  const showProcessName = ref(false); // 默认不显示流程名
  const showCancelledSteps = ref(true); // 默认显示已取消环节
  const showRejectedSteps = ref(true); // 默认显示已退回环节
  // 计算属性
  const canGenerate = computed(() => {
    switch (inputMethod.value) {
      case 'database':
        return selectedWorkflow.value && dbStatus.value === 'connected';
      case 'upload':
        return xmlContent.value.trim() !== '';
      case 'text':
        return xmlContent.value.trim() !== '';
      default:
        return false;
    }
  });

  const dbStatusText = computed(() => {
    switch (dbStatus.value) {
      case 'connected':
        return '已连接';
      case 'disconnected':
        return '未连接';
      default:
        return '测试连接';
    }
  });

  const workflowOptions = computed(() => {
    return workflowList.value
      .map((workflow) => {
        const wfid = workflow.wfid || workflow.WFID;
        const wfname = workflow.wfname || workflow.WFNAME;

        return {
          label: `${wfname} (${wfid})`,
          value: wfid,
          searchText: `${wfname} ${wfid}`,
        };
      })
      .filter((option) => option.label && option.value);
  });

  // 表格列定义
  const transitionColumns: DataTableColumns<Transition> = [
    {
      title: '流程名称',
      key: 'name',
      width: 200,
      ellipsis: {
        tooltip: true,
      },
    },
    {
      title: '别名',
      key: 'alias',
      width: 120,
    },
    {
      title: '起始状态',
      key: 'fromState',
      width: 150,
      ellipsis: {
        tooltip: true,
      },
    },
    {
      title: '目标状态',
      key: 'toState',
      width: 150,
      ellipsis: {
        tooltip: true,
      },
    },
  ];

  // 渲染Mermaid图表
  const renderMermaidChart = async (targetContainer?: HTMLElement) => {
    const container = targetContainer || mermaidContainer.value;
    if (!mermaidCode.value || !container) {
      console.warn('渲染失败：缺少Mermaid代码或容器');
      return;
    }

    try {
      console.log('开始渲染Mermaid图表');

      // 确保在浏览器环境中运行
      if (typeof window === 'undefined' || typeof document === 'undefined') {
        throw new Error('非浏览器环境，无法渲染图表');
      }

      // 更全面的DOM API检查
      if (
        !document.createElementNS ||
        !document.createElement ||
        !document.body ||
        !document.documentElement
      ) {
        throw new Error('DOM API不完整，请刷新页面重试');
      }

      // 确保Mermaid已正确加载 - 改进检查方式
      if (
        !mermaid ||
        typeof mermaid !== 'object' ||
        typeof mermaid.render !== 'function' ||
        typeof mermaid.initialize !== 'function'
      ) {
        console.error('Mermaid库检查失败:', {
          mermaidExists: !!mermaid,
          renderExists: !!(mermaid && mermaid.render),
          initializeExists: !!(mermaid && mermaid.initialize),
        });
        throw new Error('Mermaid库未正确加载，请刷新页面重试');
      }

      // 清空容器
      container.innerHTML = '';

      // 验证Mermaid代码
      if (!mermaidCode.value.trim()) {
        throw new Error('Mermaid代码为空');
      }

      // 等待DOM更新
      await nextTick();

      // 再次检查DOM环境
      if (typeof document === 'undefined' || !document.createElementNS) {
        throw new Error('DOM环境在渲染过程中变为不可用');
      }

      // 生成唯一ID
      const id = `mermaid-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      console.log('生成的ID:', id);

      // 使用try-catch包装mermaid.render调用
      let renderResult;
      try {
        console.log('调用mermaid.render，代码长度:', mermaidCode.value.length);
        renderResult = await mermaid.render(id, mermaidCode.value);
        console.log('mermaid.render调用成功');
      } catch (renderError) {
        console.error('mermaid.render调用失败:', renderError);
        // 尝试重新初始化mermaid
        await reinitializeMermaid();
        // 重试渲染
        renderResult = await mermaid.render(id, mermaidCode.value);
      }

      if (!renderResult || !renderResult.svg) {
        throw new Error('Mermaid渲染返回空结果');
      }

      // 将SVG直接插入容器
      container.innerHTML = renderResult.svg;
      console.log('SVG已插入容器');

      // 查找SVG元素并添加无障碍属性
      const svgElement = container.querySelector('svg');
      if (svgElement) {
        svgElement.setAttribute('role', 'img');
        svgElement.setAttribute('aria-label', '工作流程图');
        svgElement.style.display = 'block';
        svgElement.style.margin = '0 auto';
        svgElement.style.maxWidth = '100%';
        svgElement.style.height = 'auto';

        console.log('SVG元素配置完成，尺寸:', {
          width: svgElement.getAttribute('width'),
          height: svgElement.getAttribute('height'),
          viewBox: svgElement.getAttribute('viewBox'),
        });

        // 确保SVG居中显示
        container.style.textAlign = 'center';
        container.style.overflow = 'visible';

        // 根据容器宽度进行缩放
        const containerWidth = container.clientWidth;
        const svgWidth = svgElement.getBoundingClientRect().width;

        if (svgWidth > containerWidth && containerWidth > 0) {
          const scale = (containerWidth - 40) / svgWidth; // 留40px边距
          svgElement.style.transform = `scale(${scale})`;
          svgElement.style.transformOrigin = 'center top';
          console.log('应用缩放:', scale);
        }
      } else {
        console.warn('未找到SVG元素');
      }

      console.log('渲染完成，容器内容:', container.innerHTML.substring(0, 200));
    } catch (error) {
      console.error('渲染失败:', error);

      // 显示友好的错误信息
      container.innerHTML = `
      <div style="
        padding: 20px;
        text-align: center;
        color: #d32f2f;
        background: #ffebee;
        border: 1px solid #ffcdd2;
        border-radius: 4px;
        margin: 20px 0;
      ">
        <h3 style="margin: 0 0 10px 0; color: #d32f2f;">流程图渲染失败</h3>
        <p style="margin: 0 0 10px 0; color: #666;">错误信息: ${error.message}</p>
        <p style="margin: 0 0 10px 0; color: #666; font-size: 12px;">建议：请刷新页面后重试</p>
        <details>
          <summary style="cursor: pointer; color: #1976d2;">查看详细信息</summary>
          <pre style="background: white; padding: 10px; margin: 10px 0 0 0; border: 1px solid #ddd; border-radius: 4px; overflow: auto; max-height: 200px;">错误类型: ${error.name}\n错误堆栈: ${error.stack}</pre>
        </details>
      </div>
    `;
      message.error(`流程图渲染失败: ${error.message}`);
    }
  };

  // 重新初始化Mermaid的辅助函数
  const reinitializeMermaid = async () => {
    try {
      console.log('重新初始化Mermaid...');

      // 检查mermaid是否可用
      if (!mermaid || typeof mermaid.initialize !== 'function') {
        throw new Error('Mermaid库不可用');
      }

      await mermaid.initialize({
        startOnLoad: false,
        theme: 'default',
        securityLevel: 'loose',
        fontFamily: 'Arial, sans-serif',
        flowchart: {
          useMaxWidth: false,
          htmlLabels: true,
          curve: 'basis',
        },
      });

      console.log('Mermaid重新初始化成功');
    } catch (error) {
      console.error('Mermaid重新初始化失败:', error);
      throw error;
    }
  };
  // 创建防抖的渲染函数
  const debouncedRenderMermaidChart = debounce(renderMermaidChart, 300);

  // 打开全屏预览
  const openFullscreen = async () => {
    if (!mermaidCode.value) return;

    showFullscreen.value = true;
    await nextTick();
    await renderMermaidChart(fullscreenMermaidContainer.value);
  };

  // 下载SVG图片功能
  const downloadImage = async () => {
    if (!mermaidCode.value) return;

    let tempContainer: HTMLElement | null = null;

    try {
      // 创建临时容器用于生成图片
      tempContainer = document.createElement('div');
      tempContainer.style.position = 'absolute';
      tempContainer.style.left = '-9999px';
      tempContainer.style.top = '-9999px';
      tempContainer.style.backgroundColor = 'white';
      tempContainer.style.padding = '20px';
      document.body.appendChild(tempContainer);

      // 生成唯一ID
      const id = `mermaid-download-${Date.now()}`;

      // 创建div元素用于渲染
      const div = document.createElement('div');
      div.id = id;
      div.className = 'mermaid';
      div.textContent = mermaidCode.value;
      tempContainer.appendChild(div);

      // 渲染Mermaid图表
      const { svg } = await mermaid.render(id, mermaidCode.value);

      // 直接下载SVG文件
      const svgBlob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
      const downloadUrl = URL.createObjectURL(svgBlob);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = 'flowchart.svg';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(downloadUrl);

      message.success('流程图已下载为SVG格式');
    } catch (error) {
      console.error('下载SVG图片失败:', error);
      message.error('下载SVG图片失败');
    } finally {
      // 确保临时容器被清理
      if (tempContainer && tempContainer.parentNode) {
        document.body.removeChild(tempContainer);
      }
    }
  };

  // 监听标签页切换
  watch(activeTab, async (newTab) => {
    if (newTab === 'preview' && mermaidCode.value) {
      await nextTick();
      debouncedRenderMermaidChart();
    }
  });

  // 监听工作流选择变化
  watch(selectedWorkflow, async (newWorkflowId, oldWorkflowId) => {
    if (newWorkflowId && newWorkflowId !== oldWorkflowId && inputMethod.value === 'database') {
      // 清空之前的内容
      xmlContent.value = '';
      mermaidCode.value = '';
      transitions.value = [];

      // 清空图表容器
      if (mermaidContainer.value) {
        mermaidContainer.value.innerHTML = '';
      }

      // 自动生成新的流程图
      await generateMermaid();
    }
  });
  // 监听显示流程名选项变化
  watch(showProcessName, async () => {
    // 如果已有转换数据，重新生成Mermaid代码和图表
    if (transitions.value.length > 0) {
      const generatedCode = generateMermaidFromTransitions(transitions.value);
      mermaidCode.value = generatedCode;

      if (generatedCode) {
        // 等待DOM更新后重新渲染图表
        await nextTick();
        debouncedRenderMermaidChart();
      }
    }
  });
    // 监听显示已取消环节选项变化
  watch(showCancelledSteps, async () => {
    if (transitions.value.length > 0) {
      const generatedCode = generateMermaidFromTransitions(transitions.value);
      mermaidCode.value = generatedCode;
      
      if (generatedCode) {
        await nextTick();
        debouncedRenderMermaidChart();
      }
    }
  });

  // 监听显示已退回环节选项变化
  watch(showRejectedSteps, async () => {
    if (transitions.value.length > 0) {
      const generatedCode = generateMermaidFromTransitions(transitions.value);
      mermaidCode.value = generatedCode;
      
      if (generatedCode) {
        await nextTick();
        debouncedRenderMermaidChart();
      }
    }
  });

  // 数据库连接测试
  const testConnection = async () => {
    isTestingConnection.value = true;
    try {
      const settings = await invoke<UserSettings>('get_user_settings');
      const result = await invoke<boolean>('test_database_connection', {
        config: settings.database,
      });
      dbStatus.value = 'connected';
      message.success('数据库连接成功');
    } catch (error) {
      dbStatus.value = 'disconnected';
      console.error('数据库连接失败:', error);
      message.error(`连接测试失败: ${error}`);
    } finally {
      isTestingConnection.value = false;
    }
  };

  // 加载工作流列表
  const loadWorkflowList = async () => {
    isLoadingWorkflows.value = true;
    try {
      const result = await invoke<WorkflowModel[]>('get_workflow_list');
      workflowList.value = result || [];
      message.success(`工作流列表加载成功，共 ${workflowList.value.length} 个工作流`);
    } catch (error) {
      console.error('加载工作流列表失败:', error);
      message.error(`加载工作流列表失败: ${error}`);
    } finally {
      isLoadingWorkflows.value = false;
    }
  };

  // 加载工作流XML
  const loadWorkflowXml = async () => {
    if (!selectedWorkflow.value) {
      message.error('请先选择工作流程');
      return;
    }

    try {
      const result = await invoke<WorkflowXmlResult>('get_workflow_xml', {
        wfid: selectedWorkflow.value,
      });
      console.log('后端返回的数据:', result);

      // 兼容多种字段名格式
      const wfcontent = result?.wfcontent || result?.WFCONTENT || result?.WfContent;

      if (wfcontent && wfcontent.trim()) {
        xmlContent.value = wfcontent;
        message.success('工作流XML加载成功');
      } else {
        console.warn('未找到有效的XML内容:', result);
        message.warning('未找到工作流XML内容，请检查工作流是否包含有效的XML数据');
      }
    } catch (error) {
      console.error('加载工作流XML失败:', error);
      message.error(`加载工作流XML失败: ${error}`);
    }
  };

  const handleFileChange = (options: { fileList: UploadFileInfo[] }) => {
    fileList.value = options.fileList;

    if (options.fileList.length > 0) {
      const file = options.fileList[0];
      if (file.file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          xmlContent.value = e.target?.result as string;
          message.success('文件读取成功');
        };
        reader.onerror = () => {
          message.error('文件读取失败');
        };
        reader.readAsText(file.file);
      }
    }
  };

  const handleFileRemove = () => {
    fileList.value = [];
    xmlContent.value = '';
  };

  const parseXmlTransitions = (xmlText: string): Transition[] => {
    const transitions: Transition[] = [];

    try {
      // 使用正则表达式解析transition节点
      const transitionRegex = /<transition[\s\S]*?<\/transition>/g;
      const nameRegex = /<name>([\s\S]*?)<\/name>/;
      const aliasRegex = /<alias>([\s\S]*?)<\/alias>/;
      const fromStateRegex = /<from_state>([\s\S]*?)<\/from_state>/;
      const toStateRegex = /<to_state>([\s\S]*?)<\/to_state>/;
      const descriptionRegex = /<description>([\s\S]*?)<\/description>/;

      const transitionMatches = xmlText.match(transitionRegex);

      if (transitionMatches) {
        transitionMatches.forEach((transitionXml) => {
          const nameMatch = transitionXml.match(nameRegex);
          const aliasMatch = transitionXml.match(aliasRegex);
          const fromStateMatch = transitionXml.match(fromStateRegex);
          const toStateMatch = transitionXml.match(toStateRegex);
          const descriptionMatch = transitionXml.match(descriptionRegex);

          if (nameMatch && fromStateMatch && toStateMatch) {
            const name = nameMatch[1].trim();

            transitions.push({
              name: name,
              alias: aliasMatch ? aliasMatch[1].trim() : '',
              fromState: fromStateMatch[1].trim(),
              toState: toStateMatch[1].trim(),
              description: descriptionMatch ? descriptionMatch[1].trim() : '',
            });
          }
        });
      }
    } catch (error) {
      console.error('解析XML失败:', error);
      message.error('XML解析失败');
    }

    return transitions;
  };

  // 生成Mermaid代码从转换数据
  const generateMermaidFromTransitions = (transitions: Transition[]): string => {
    if (!transitions || transitions.length === 0) {
      console.warn('没有转换数据可用于生成Mermaid代码');
      return '';
    }

    // 根据选项过滤转换数据
    let filteredTransitions = transitions.filter(t => {
      // 检查是否为已取消环节（可以根据实际的状态名称或描述来判断）
      const isCancelled = t.toState.includes('取消') || t.toState.includes('CANCELLED') || 
                         t.fromState.includes('取消') || t.fromState.includes('CANCELLED');
      
      // 检查是否为已退回环节
      const isRejected = t.toState.includes('退回') || t.toState.includes('REJECTED') || 
                        t.fromState.includes('退回') || t.fromState.includes('REJECTED');
      
      // 根据用户选择决定是否包含这些环节
      if (isCancelled && !showCancelledSteps.value) {
        return false;
      }
      if (isRejected && !showRejectedSteps.value) {
        return false;
      }
      
      return true;
    });

    console.log('开始生成Mermaid代码，转换数量:', filteredTransitions.length);
    console.log('转换数据:', filteredTransitions);

    let mermaidCode = 'flowchart TD\n';

    // 收集所有状态（使用过滤后的转换数据）
    const states = new Set<string>();
    filteredTransitions.forEach((t) => {
      if (t.fromState) states.add(t.fromState);
      if (t.toState) states.add(t.toState);
    });

    console.log('收集到的状态:', Array.from(states));

    if (states.size === 0) {
      console.warn('没有找到任何状态');
      return '';
    }

    // 创建状态映射
    const stateMap = new Map<string, string>();
    let stateIndex = 1;
    states.forEach((state) => {
      const shortName = `S${stateIndex++}`;
      stateMap.set(state, shortName);

      // 处理状态显示名称
      let displayName = state.trim();

      // 特殊处理：将START_HERE转换为新建
      if (displayName === 'START_HERE' || state === 'START_HERE') {
        displayName = '新建';
      } else {
        // 处理 流程名_环节名 格式
        if (displayName.includes('_')) {
          const parts = displayName.split('_');
          if (parts.length >= 2) {
            const processName = parts[0]; // 流程名
            const stepName = parts.slice(1).join('_'); // 环节名（处理可能有多个下划线的情况）

            if (showProcessName.value) {
              // 显示完整名称：流程名_环节名
              displayName = `${processName}_${stepName}`;
            } else {
              // 只显示环节名
              displayName = stepName;
            }
          }
        }

        // 去掉常见的前缀
        displayName = displayName.replace(/^待/, '');
      }

      if (!displayName) {
        displayName = `状态${stateIndex - 1}`;
      }

      // 转义特殊字符
      displayName = displayName.replace(/"/g, '&quot;');
      mermaidCode += `    ${shortName}["${displayName}"]\n`;
    });

    mermaidCode += '\n';

    // 生成连接线
    let connectionCount = 0;
    transitions.forEach((t) => {
      const fromNode = stateMap.get(t.fromState);
      const toNode = stateMap.get(t.toState);
      let label = (t.alias || '流转').trim();

      if (!label) {
        label = '流转';
      }

      // 转义特殊字符
      label = label.replace(/"/g, '&quot;');

      if (fromNode && toNode && fromNode !== toNode) {
        mermaidCode += `    ${fromNode} -->|"${label}"| ${toNode}\n`;
        connectionCount++;
      }
    });

    console.log('生成的Mermaid代码:');
    console.log(mermaidCode);
    console.log('连接数量:', connectionCount);

    // 验证生成的代码
    if (connectionCount === 0) {
      console.warn('没有生成任何连接线');
      // 如果没有连接，至少显示所有状态
      if (states.size > 0) {
        return mermaidCode;
      } else {
        return '';
      }
    }

    return mermaidCode;
  };

  const generateMermaid = async () => {
    if (!canGenerate.value) return;

    isGenerating.value = true;
    try {
      // 如果是数据库模式，先加载XML
      if (inputMethod.value === 'database') {
        await loadWorkflowXml();
      }

      if (!xmlContent.value.trim()) {
        message.warning('XML内容为空，无法生成流程图');
        return;
      }

      // 解析XML
      const parsedTransitions = parseXmlTransitions(xmlContent.value);
      transitions.value = parsedTransitions;

      if (parsedTransitions.length === 0) {
        message.warning('未找到有效的流程转换信息');
        return;
      }

      // 生成Mermaid代码
      const generatedCode = generateMermaidFromTransitions(parsedTransitions);
      mermaidCode.value = generatedCode;

      if (generatedCode) {
        message.success(`流程图生成成功，共解析 ${parsedTransitions.length} 个流程转换`);

        // 如果当前在预览标签页，立即渲染
        if (activeTab.value === 'preview') {
          await nextTick();
          await renderMermaidChart();
        }
      } else {
        message.error('生成Mermaid代码失败');
      }
    } catch (error) {
      console.error('生成流程图失败:', error);
      message.error(`生成流程图失败: ${error}`);
    } finally {
      isGenerating.value = false;
    }
  };

  const copyMermaidCode = async () => {
    if (!mermaidCode.value) return;

    try {
      await navigator.clipboard.writeText(mermaidCode.value);
      message.success('Mermaid代码已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败，请手动复制');
    }
  };

  const downloadMermaidCode = () => {
    if (!mermaidCode.value) return;

    try {
      const blob = new Blob([mermaidCode.value], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'mermaid-code.txt';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      message.success('Mermaid代码已下载');
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败');
    }
  };

  const clearAll = () => {
    xmlContent.value = '';
    mermaidCode.value = '';
    transitions.value = [];
    fileList.value = [];
    selectedWorkflow.value = '';

    // 清空图表容器
    if (mermaidContainer.value) {
      mermaidContainer.value.innerHTML = '';
    }
    if (fullscreenMermaidContainer.value) {
      fullscreenMermaidContainer.value.innerHTML = '';
    }

    message.success('已清空所有内容');
  };

  // 组件挂载时的初始化
  onMounted(async () => {
    try {
      // 等待DOM完全加载
      await nextTick();

      // 确保mermaid库已加载
      if (!mermaid || typeof mermaid.initialize !== 'function') {
        console.error('Mermaid库未正确导入');
        message.error('Mermaid库加载失败，请刷新页面重试');
        return;
      }

      // 初始化 Mermaid
      await mermaid.initialize({
        startOnLoad: false,
        theme: 'default',
        securityLevel: 'loose',
        fontFamily: 'Arial, sans-serif',
        flowchart: {
          useMaxWidth: false, // 改为false避免尺寸问题
          htmlLabels: true,
          curve: 'basis',
        },
        themeVariables: {
          primaryColor: '#ff6b6b',
          primaryTextColor: '#fff',
          primaryBorderColor: '#ff4757',
          lineColor: '#5f27cd',
          secondaryColor: '#00d2d3',
          tertiaryColor: '#fff',
        },
      });

      console.log('Mermaid初始化成功');

      // 测试数据库连接
      await testConnection();

      // 如果连接成功，自动切换到数据库模式并加载工作流列表
      if (dbStatus.value === 'connected') {
        inputMethod.value = 'database';
        await loadWorkflowList();
      }
    } catch (error) {
      console.error('组件初始化失败:', error);
      message.error('组件初始化失败，请刷新页面重试');
    }
  });
</script>

<style scoped>
  .xml-to-mermaid-container {
    height: 100%;
    padding: 16px;
  }

  .main-content {
    display: flex;
    gap: 16px;
    height: 100%;
  }

  .left-panel {
    flex: 0 0 400px;
    height: fit-content;
  }

  .right-panel {
    flex: 1;
    min-width: 0;
  }

  .input-card,
  .result-card {
    height: 100%;
  }

  .section {
    margin-bottom: 16px;
  }

  .section-title {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
  }

  .mermaid-preview {
    position: relative;
  }

  .preview-header {
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e0e0e0;
  }

  .mermaid-container,
  .fullscreen-mermaid-container {
    min-height: 500px;
    width: 100%;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 20px;
    background: #ffffff;
    overflow: visible;
    position: relative;
  }

  .fullscreen-content {
    height: calc(90vh - 120px);
    overflow: auto;
  }

  .fullscreen-mermaid-container {
    height: 100%;
    min-height: auto;
  }

  .fullscreen-modal {
    max-width: none !important;
  }

  /* 无障碍性 - 屏幕阅读器专用 */
  .sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
  }

  /* Mermaid 图表样式优化 */
  :deep(.mermaid) {
    width: 100%;
    min-height: 400px;
    background: transparent;
    position: relative;
    overflow: visible;
  }

  :deep(.mermaid svg) {
    width: 100% !important;
    height: auto !important;
    max-width: none !important;
    background: transparent !important;
    display: block !important;
    margin: 0 auto;
    overflow: visible;
  }

  /* 确保SVG内容可见 */
  :deep(.mermaid svg g) {
    visibility: visible !important;
  }

  :deep(.mermaid svg .node) {
    fill: #f9f9f9 !important;
    stroke: #333 !important;
    stroke-width: 2px !important;
  }

  :deep(.mermaid svg .edgePath path) {
    stroke: #333 !important;
    stroke-width: 2px !important;
  }

  :deep(.mermaid svg .edgeLabel) {
    background-color: white !important;
    color: #333 !important;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .main-content {
      flex-direction: column;
    }

    .left-panel {
      flex: none;
    }
  }
</style>
